package com.wt.servlet;


import com.alibaba.fastjson.JSONObject;
import com.wt.entity.WqunAccount;
import com.wt.util.R.R;
import com.wt.util.axios.Return;
import com.wt.util.oos.Upload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@WebServlet({"/util/uploadImg","/util/uploadFile"})
public class UploadServlet  extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject jsonObject = null;
        HashMap<String, String> map = null;
        WqunAccount wqunAccount = new WqunAccount();

        //System.out.println(req.getRequestURL().substring(req.getRequestURL().lastIndexOf("/")+1));
        switch (req.getRequestURL().substring(req.getRequestURL().lastIndexOf("/")+1)){
            case "uploadImg":
                try {
//                    try {
//                        jsonObject = Axios.post(req);//Json接受
//                    } catch (IOException e) {
//                        Return.R(resp,R.error().message(ResultMess.DARA_FORMAT_ERROR.getDesc()));
//                    }
                    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();//实例化一个文件上传的工厂类
                    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
                    List<FileItem> list = servletFileUpload.parseRequest(req);
                    for (FileItem item : list) {
                        boolean ifFile = item.isFormField();
                        if(!ifFile){
                            String folder =req.getServletContext().getRealPath("/upload/img");
                            File imgFolder = new File(folder);// 文件夹
                            String fname = item.getName();// 获取文件名
                            String ext = "." + fname.substring(fname.lastIndexOf(".")+1);// 获取文件后缀
                            String dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now());// 获取时间字符串
                            String newFileName = dateTimeFormatter + UUID.randomUUID().toString().replaceAll("-","") + ext;// 生成新的文件名
                            File filePath = new File(imgFolder, newFileName);// 文件在本机的全路径
                            if (!filePath.getParentFile().exists()){
                                filePath.getParentFile().mkdirs();
                            }
                            item.write(filePath);
                            String resPath = Upload.UploadImg(filePath);
                            //filePath.delete();
                            Return.R(resp,R.ok().data("resPath",resPath));
                        }else{
                            Return.R(resp,R.error());
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                break;
            case "uploadFile":
                try {
//                    try {
//                        jsonObject = Axios.post(req);//Json接受
//                    } catch (IOException e) {
//                        Return.R(resp,R.error().message(ResultMess.DARA_FORMAT_ERROR.getDesc()));
//                    }
                    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();//实例化一个文件上传的工厂类
                    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
                    List<FileItem> list = servletFileUpload.parseRequest(req);
                    for (FileItem item : list) {
                        boolean ifFile = item.isFormField();
                        if(!ifFile){
                            String folder =req.getServletContext().getRealPath("/upload/img");
                            File imgFolder = new File(folder);// 文件夹
                            String fname = item.getName();// 获取文件名
                            String ext = "." + fname.substring(fname.lastIndexOf(".")+1);// 获取文件后缀
                            String dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now());// 获取时间字符串
                            String newFileName = dateTimeFormatter + UUID.randomUUID().toString().replaceAll("-","") + ext;// 生成新的文件名
                            File filePath = new File(imgFolder, newFileName);// 文件在本机的全路径
                            if (!filePath.getParentFile().exists()){
                                filePath.getParentFile().mkdirs();
                            }
                            item.write(filePath);
                            String resPath = Upload.UploadFile(filePath);
                            //filePath.delete();
                            Return.R(resp,R.ok().data("resPath",resPath));
                        }else{
                            Return.R(resp,R.error());
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                break;

        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
